package com.heihei.authority.core.validate.code.image;

import com.heihei.authority.core.properties.MySecurityProperties;
import com.heihei.authority.core.validate.code.ValidateCodeGenerator;
import com.heihei.authority.core.validate.code.generate.VerifyCodeUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.awt.image.BufferedImage;

/**
 *  图形验证码  系统集成默认实现
 *
 * @version 1.0
 * @since JDK1.8
 * @author duanhengfei
 * @date 2021年04月11日 11:03:31
 */
public class ImageCodeGenerator implements ValidateCodeGenerator {

    private MySecurityProperties mySecurityProperties;

    @Override
    public ImageCode generateCode(ServletWebRequest request) {
        int length = ServletRequestUtils.getIntParameter(request.getRequest(), "length", mySecurityProperties.getCode().getImage().getLength());
        int width = ServletRequestUtils.getIntParameter(request.getRequest(), "width", mySecurityProperties.getCode().getImage().getWidth());
        int height = ServletRequestUtils.getIntParameter(request.getRequest(), "height", mySecurityProperties.getCode().getImage().getHeight());
        int expireIn = ServletRequestUtils.getIntParameter(request.getRequest(), "expireIn", mySecurityProperties.getCode().getImage().getExpireIn());

        String verifyCode = VerifyCodeUtils.generateVerifyCode(length);
        BufferedImage image = VerifyCodeUtils.generateBufferedImage(width, height, verifyCode);
        return new ImageCode(image, verifyCode, expireIn);
    }

    public MySecurityProperties getMySecurityProperties() {
        return mySecurityProperties;
    }

    public void setMySecurityProperties(MySecurityProperties mySecurityProperties) {
        this.mySecurityProperties = mySecurityProperties;
    }
}
